package service

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/lzppppppp/virapaksa-go/internal/monitor_check/handler"
)

func GetData(docPath, typeOfData string) {
	file, err := os.Open(docPath)
	if err != nil {
		fmt.Errorf("Error opening file: %v", err)
	}
	defer file.Close()

	var lines []string
	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}

	if err := scanner.Err(); err != nil {
		fmt.Errorf("Error reading file: %v", err)
	}

	if typeOfData == "process" {
		for _, v := range lines {
			var keywordsArr []string
			targetUrl := "http://" + v + ":10905/metrics"
			data, err := handler.GetData(targetUrl)
			if err != nil {
				fmt.Println(err)
			}
			dataArr := strings.Split(data, "\n")

			for _, vv := range dataArr {
				if strings.HasPrefix(vv, "process_active_count") {
					singleDataArr := strings.Split(vv, "\"")
					keywordsArr = append(keywordsArr, "\""+singleDataArr[1]+"\"")
				}
			}
			fmt.Println(keywordsArr)
			log.Printf("Info: %v %v", v, keywordsArr)
		}
	} else if typeOfData == "port" {
		for _, v := range lines {
			var keywordsArr []string
			targetUrl := "http://" + v + ":10914/metrics"
			data, err := handler.GetData(targetUrl)
			if err != nil {
				fmt.Println(err)
			}
			dataArr := strings.Split(data, "\n")

			for _, vv := range dataArr {
				if strings.HasPrefix(vv, "port_up") {
					singleDataArr := strings.Split(vv, "\"")
					fmt.Println(singleDataArr[1])
					keywordsArr = append(keywordsArr, "\""+singleDataArr[1]+"\"")
				}
			}
			log.Printf("Info: %v %v", v, keywordsArr)
		}
	} else if typeOfData == "sys" {
		for _, v := range lines {

			targetUrl := "http://" + v + ":10916/metrics"
			_, err := handler.GetData(targetUrl)
			if err != nil {
				fmt.Printf("Info: %v port check failed\n", v)
				log.Printf("Info: %v port check failed\n", v)
			} else {
				fmt.Printf("Info: %v port check success\n", v)
				log.Printf("Info: %v port check success\n", v)
			}
		}
	} else if typeOfData == "node" {
		for _, v := range lines {

			targetUrl := "http://" + v + ":10900/metrics"
			_, err := handler.GetData(targetUrl)
			if err != nil {
				fmt.Printf("Info: %v node check failed\n", v)
				log.Printf("Info: %v node check failed\n", v)
			} else {
				fmt.Printf("Info: %v node check success\n", v)
				log.Printf("Info: %v node check success\n", v)
			}
		}
	}

}
